package com.neusoft.his.sb.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.his.sb.entity.CommonResult;
import com.neusoft.his.sb.entity.Emp;
import com.neusoft.his.sb.mapper.EmpMapper;
import com.neusoft.his.sb.service.EmpService;
@Service
public class EmpServiceImpl implements EmpService {
	@Autowired
	EmpMapper empMapper;

	@Override
	public CommonResult getById(int empno) {
		Emp emp = empMapper.getById(empno);
		CommonResult result =  new CommonResult<Emp>(emp);
		return result;
	}

	@Override
	public CommonResult getByIdWithLeader(int empno) {
		Emp emp = empMapper.getByIdWithLeader(empno);
		CommonResult result =  new CommonResult<Emp>(emp);
		return result;
	}

	@Override
	public CommonResult getByIdWithEmp(int empno) {
		Emp emp = empMapper.getByIdWithEmp(empno);
		CommonResult result =  new CommonResult<Emp>(emp);
		return result;
	}
	/**
	 * 将列表转换为一棵树
	 */
	@Override
	public CommonResult getByIdInTree(int empno) {
		List<Emp> les =  empMapper.getAll();
		Emp  root = null;
		for (Emp emp : les) {
			if ( emp.getEmpno().intValue() == empno) {
				root =  emp;
				break;
			}
		}
		
		fillChildre( root, les );
		
		CommonResult result =  new CommonResult<Emp>(root);
		return result;
	}

	private void fillChildre(Emp root, List<Emp> les) {
		// 判断员工下属集合是否为空
		if (root.getLes()==null) {
			root.setLes(  new ArrayList<Emp>() );
		}
		// 遍历集合，填充root的下属员工
		for (Emp emp : les) {
			if (emp.getMgr()!=null && emp.getMgr().intValue() ==  root.getEmpno().intValue()) {
				root.getLes().add(emp);
				//les.remove(emp);
			}
		}
		// 遍历root下属员工的集合，为下属员工填充下属员工
		for (Emp emp : root.getLes()) {
			fillChildre( emp ,   les);
		}
		
	}

}
